package main

/*
#include "ThostFtdcUserApiStruct.h"
extern void OnMktgo(struct CThostFtdcDepthMarketDataField* pMkt);
*/
import "C"
import (
	"CTP/mdapi"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"time"

	"github.com/gorilla/impl"
	"github.com/gorilla/websocket"
)

//export  OnMktgo
func OnMktgo(pMkt *C.struct_CThostFtdcDepthMarketDataField) {

	fmt.Println(C.GoString(&pMkt.InstrumentID[0]), "  ", float64(pMkt.OpenPrice), "  ", float64(pMkt.HighestPrice), "  ", float64(pMkt.LowestPrice), "  ", float64(pMkt.LastPrice), "  ", int(pMkt.Volume))
	if conn1 != nil {
		err := conn1.WriteMessage([]byte(C.GoString(&pMkt.InstrumentID[0]) + "  " + strconv.FormatFloat(float64(pMkt.LastPrice), 'f', -1, 64) + "  " + strconv.Itoa(int(pMkt.Volume))))
		fmt.Println("*************", err)
	}

}

var (
	upgrader = websocket.Upgrader{}
	conn1    *impl.Connection
)

func wsHandler(w http.ResponseWriter, r *http.Request) {
	//	w.Write([]byte("hello"))
	var (
		wsConn *websocket.Conn
		err    error
		conn   *impl.Connection
		data   []byte
	)
	// 完成ws协议的握手操作
	// Upgrade:websocket
	if wsConn, err = upgrader.Upgrade(w, r, nil); err != nil {
		fmt.Println("*************", err)
		return
	}

	if conn, err = impl.InitConnection(wsConn); err != nil {
		fmt.Println("*************", err)
		goto ERR
	}
	fmt.Println("*************", err)
	conn1 = conn
	for {
		if data, err = conn.ReadMessage(); err != nil {
			goto ERR
		}
		if err = conn.WriteMessage(data); err != nil {
			goto ERR
		}
	}

ERR:
	fmt.Println("*************", err)
	conn.Close()

}

func main() {
	//"log"
	//"net/http"
	//_ "net/http/pprof"
	//go func() {
	//log.Println(http.ListenAndServe("localhost:6060", nil))
	//}()

	md := mdapi.NewMdapi()
	//defer md.FreeMdapi()
	//md.ConnectMdBgo("E:\\godev\\ctptest\\test\\", "tcp://180.168.146.187:10110")
	md.ConnectMdgo("E:\\godev\\ctptest\\test\\", "tcp://180.168.146.187:10131")
	md.InitMdgo()
	//md.JoinMdgo()
	//fmt.Println("step1", md.GetVersionMdMdgo())
	time.Sleep(time.Duration(2) * time.Second)

	loginfield := mdapi.CThostFtdcReqUserLoginFieldgo{BrokerID: "9999", UserID: "xxx", Password: "xxxxx"}
	md.LoginMdgo(loginfield, 0)
	fmt.Println("step2")
	time.Sleep(time.Duration(2) * time.Second)
	syb := []string{"rb2001"}
	md.RegMarketDataMdgo(mdapi.OnMkt(C.OnMktgo))
	md.SubscribeMarketDataMdgo(syb)
	fmt.Println("step3")

	http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "test.html")
	})
	http.HandleFunc("/ws", wsHandler)
	http.ListenAndServe(":8080", nil)
	//time.Sleep(time.Duration(2) * time.Second)
	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	fmt.Println("按Ctrl+C可退出程序")
	<-quit
	fmt.Println("主程序退出")
}
